/**
 * 
 */
package it.unisalento.appsalento.asynctask;

import it.unisalento.appsalento.constants.Constants;
import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.activity.MainActivity;
import it.unisalento.appsalento.activity.dialog.GenericDialog;
import it.unisalento.appsalento.asynctask.framework.MIMETypes;
import it.unisalento.appsalento.model.Request;
import it.unisalento.appsalento.model.Response;

import java.io.IOException;
import java.lang.ref.WeakReference;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

/**
 * @author AGM
 * 
 */
public class PrenotaEsameAsyncTask  extends  ActionAsyncTask {

	
	public PrenotaEsameAsyncTask(String idAppello,MainActivity main ) {
		super.idAppello = idAppello;
		super.mainActivityWeakRef= new WeakReference<MainActivity >(main);
	}
	

	@Override
	protected Boolean doInBackground(Void... params) {
		ObjectMapper mapper = new ObjectMapper();
		boolean retVal = false;
		try {
			retVal = setData( mapper);
		} catch (Throwable e) {
			e.printStackTrace();
			new GenericDialog(mainActivityWeakRef.get(), "",Constants.TITLE_ERROR);
		} 

		return retVal;
	}
	
	public boolean setData( ObjectMapper mapper) throws JsonParseException, JsonMappingException, IOException{
		boolean retVal = false;
			if(!Constants.MOCK_ENABLED){
				Request request = new Request();
				request.setUtente(App.utente);
				request.setIdAppello(idAppello);
				final Gson gson = new GsonBuilder().create();
				final Client client = Client.create();
			    final WebResource resource = client.resource(Constants.URL_REST + Constants.SERVICE_PRENOTA_APPELLO);
			    final ClientResponse response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(ClientResponse.class, gson.toJson(request));

			    final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
			    Response prenotazioneResponse = mapper.readValue(responseEntity,Response.class);
				if(prenotazioneResponse != null){
					retVal = prenotazioneResponse.isOk();
					mMessageResponse = prenotazioneResponse.getMessaggio();
				}
			}else{
				retVal = true;
			}
		return retVal;
	}

	
}
